#include "CameraResultThreadPool.h"

namespace libcvos_vfr
{

    CameraResultThreadPool::CameraResultThreadPool(size_t numThreads)
        : m_stop(false)
    {
        for (size_t i = 0; i < numThreads; ++i)
        {
            m_workers.emplace_back([this]
                                   { WorkerThread(); });
        }
    }

    CameraResultThreadPool::~CameraResultThreadPool()
    {
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            m_stop = true;
        }
        m_condition.notify_all();
        for (std::thread &worker : m_workers)
        {
            if (worker.joinable())
            {
                worker.join();
            }
        }
    }

    void CameraResultThreadPool::Submit(Task task, std::shared_ptr<CameraResult> result)
    {
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            m_tasks.emplace(std::make_pair(task, result));
        }
        m_condition.notify_one();
    }

    size_t CameraResultThreadPool::GetQueueSize() const
    {
        std::unique_lock<std::mutex> lock(m_mutex);
        return m_tasks.size();
    }

    size_t CameraResultThreadPool::GetThreadCount() const
    {
        return m_workers.size();
    }

    void CameraResultThreadPool::WorkerThread()
    {
        while (true)
        {
            std::pair<Task, std::shared_ptr<CameraResult>> task;
            {
                std::unique_lock<std::mutex> lock(m_mutex);
                m_condition.wait(lock, [this]
                                 { return m_stop || !m_tasks.empty(); });

                if (m_stop && m_tasks.empty())
                {
                    return;
                }

                task = std::move(m_tasks.front());
                m_tasks.pop();
            }

            try
            {
                task.first(task.second);
            }
            catch (const std::exception &e)
            {
                // LOG_FMT_ERR("Task execution failed: %s", e.what());
            }
        }
    }

} // namespace libcvos_vfr